# @Version : 1.0
# @Author ： 韩顺平
# @File : slipwordtopdf.py
# @Time ：2025/2/12  18:46
import os
from docx import Document
from docx2pdf import convert
from PyPDF2 import PdfReader, PdfWriter
def split_word_pages_to_pdfs(word_file_path, output_folder):
    # 创建输出文件夹（如果不存在）
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    # 临时PDF文件路径
    temp_pdf_path = 'temp.pdf'
    # 将Word文件转换为PDF
    convert(word_file_path, temp_pdf_path)
    # 读取临时PDF文件
    with open(temp_pdf_path, 'rb') as file:
        pdf_reader = PdfReader(file)
        num_pages = len(pdf_reader.pages)
        # 逐页拆分PDF
        for page_num in range(num_pages):
            pdf_writer = PdfWriter()
            pdf_writer.add_page(pdf_reader.pages[page_num])
            # 生成输出PDF文件路径
            output_pdf_path = os.path.join(output_folder, f'step{page_num + 1}.pdf')
            # 保存当前页为单独的PDF文件
            with open(output_pdf_path, 'wb') as output_file:
                pdf_writer.write(output_file)
    # 删除临时PDF文件
    os.remove(temp_pdf_path)
if __name__ == "__main__":
    # Word文件路径
    word_file_path = '成果申报书模板.docx'
    # 输出文件夹名称
    output_folder = 'kcshow'
    split_word_pages_to_pdfs(word_file_path, output_folder)